import {
    app, BrowserWindow, ipcMain, Tray, Menu, IpcMainInvokeEvent
    , screen, shell, BrowserView, nativeImage,globalShortcut
} from "electron";
import { registerWindowId, removeWindowId } from './windowManager'
import path from "path";
import fs from 'fs'
export const createWindowMain = (): any => {
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.workAreaSize
    let win: BrowserWindow
    let windowX: number = 0, windowY: number = 0; //中化后的窗口坐标
    let X: number, Y: number; //鼠标基于显示器的坐标
    let screenMove: any = null;  //鼠标移动监听
    let backGroundColor = '';
    return new Promise((resolve, rejects) => {
        return fs.readFile(path.join(__dirname, '../message.txt'), (err: any, str: any) => {
            if (err) rejects(err)
            else resolve(str)
        })
    }).then((str: any) => {
        let message: string = str.toString();
        let len = message.length;
        if (len == 0) {
            return new Promise((resolve) => {
                fs.appendFile(path.join(__dirname, '../message.txt'), "backGroundColor=#ffffff", (err) => {
                    if (err) throw new Error(err.toString())
                })
            })
        } else {
            return backGroundColor = message.split('=')[1]
        }
    }).then((backGroundColor: any) => {
        console.log(backGroundColor, '39');
        win = new BrowserWindow({
            width: 1020,
            height: 670,
            // backgroundColor: '#00000000',
            frame: false, //隐藏默认控件
            backgroundColor: backGroundColor,
            resizable: false,
            maxHeight: 670,
            title: '大牛马音乐',
            icon: path.join(__dirname, '../icons/favicon.ico'),
            webPreferences: {
                nodeIntegration: true,
                // contextIsolation: false,
                preload: path.join(__dirname, "../preload/index.js"),
            },
        });
        ipcMain.handle('to-close-or-small', (e, message) => {
            if (message === 'quit') {
                win.destroy();
            } else {
                win.hide();
            }
        })
        win.webContents.toggleDevTools()
        //缩略图
        function play() {
            return win.setThumbarButtons([
                {
                    tooltip: '上一首',
                    icon: nativeImage.createFromPath(path.join(__dirname, '../icons/prev.png')),
                    click() {
                        win.webContents.send('main-prev')
                    }
                },
                {
                    tooltip: '暂停',
                    icon: nativeImage.createFromPath(path.join(__dirname, '../icons/stop.png')),
                    click() {
                        stop()
                        win.webContents.send('main-play')
                    }
                },
                {
                    tooltip: '下一首',
                    icon: nativeImage.createFromPath(path.join(__dirname, '../icons/next.png')),
                    click() {
                        win.webContents.send('main-next')
                    }
                }
            ])
        }

        function stop() {
            win.setThumbarButtons([
                {
                    tooltip: '上一首',
                    icon: nativeImage.createFromPath(path.join(__dirname, '../icons/prev.png')),
                    click() {
                        win.webContents.send('main-prev')
                    }
                },
                {
                    tooltip: '播放',
                    icon: nativeImage.createFromPath(path.join(__dirname, '../icons/play.png')),
                    click() {
                        play();
                        win.webContents.send('main-play')
                    }
                },
                {
                    tooltip: '下一首',
                    icon: nativeImage.createFromPath(path.join(__dirname, '../icons/next.png')),
                    click() {
                        win.webContents.send('main-next')

                    }
                }
            ])
        }
        stop();
        ipcMain.on('render-play', () => {
            play();
        })
        ipcMain.on('render-play-fail', () => {
            stop();
        })
        win.setThumbnailClip({ x: 10, y: 0, width: 150, height: 60 })
        win.setThumbnailToolTip('大牛马音乐')
        ipcMain.on('change-play-thum', (e, message) => {
            console.log(message);

            win.setThumbnailToolTip(message)
            win.setTitle(message)
        })
        //缩略图
        ipcMain.on('to-close', () => {
            win.close();
        })
        ipcMain.on('to-small', () => {
            win.minimize();
        })
        ipcMain.on('to-middle', () => {
            win.setContentBounds({ x: windowX, y: windowY, width: 1020, height: 670 })
            win.setBounds({ x: windowX, y: windowY, width: 1020, height: 670 })
            win.webContents.send('to-changeFished-finshed')
        })
        ipcMain.on('to-big', () => {
            windowX = win.getBounds().x
            windowY = win.getBounds().y
            win.setContentBounds({ x: 0, y: 0, width, height })
            win.setBounds({ x: 0, y: 0, width, height })
            win.webContents.send('to-changeFished-finshed')
        })
        ipcMain.on('move-screen', (e, obj) => {
            let { mouseX, mouseY } = obj //鼠标按下时的坐标
            let { x, y } = win.getBounds();  //左上点坐标
            if(!screenMove){
                console.log('beginmoving');
                screenMove = setInterval(() => {
                    X = screen.getCursorScreenPoint().x
                    Y = screen.getCursorScreenPoint().y
                    let nW = win.getContentBounds().width
                    let nH = win.getContentBounds().height
                    win.setContentBounds({width:nW,height:nH,x:x + (X - (mouseX + x)),y:y + (Y - (mouseY + y))})
                }, 10)
            }
        })

        ipcMain.on('cancel-screen', () => {
            console.log('endmoving');
            
            clearInterval(screenMove)
            screenMove = null;
        })
        win.on('close', (e) => {
            e.preventDefault()
            //点击关闭按钮向渲染进程请求页面
            //选择退出模式
            let giveWayToMain = (event: Electron.IpcMainEvent, message?: string) => {
                ipcMain.removeListener('give-way-to-main', giveWayToMain)
                //选择已存在方案
                if (message === 'quit') {
                    win.destroy();
                } else if (message === 'leave') {
                    win.hide();
                } else {
                    //展示退出面板
                    event.reply('main-back-way-to-render', { ifToClose: true })
                }
            }
            win.webContents.send('check-up-quit-way')
            ipcMain.on('give-way-to-main', giveWayToMain)
        })

        //主控结束
        ipcMain.on('new-window', (e, message) => {
            e.preventDefault();
            shell.openExternal(message);
        })

        //加载背景色
        ipcMain.on('bkColor', (e, bkColor) => {
            try {
                new Promise<any>((resolve, reject) => {
                    return fs.readFile(path.join(__dirname, '../message.txt'), (err: any, str: any) => {
                        if (err) reject(err)
                        else resolve(str.toString())
                    })
                }).then((message: string) => {
                    let arr = message.split('=')
                    arr[1] = bkColor
                    let t: string = ''
                    arr.forEach((ele, index) => {
                        t += ele
                        if (index % 2 == 0) {
                            t += '='
                        }
                    })
                    console.log(t);
                    fs.writeFile(path.join(__dirname, '../message.txt'), t, (err: any) => {
                        if (err) throw new Error(err.toSting())
                    })
                })

            } catch (error) {
                console.log(error);
            }
        })

        if (app.isPackaged) {
            win.loadFile(path.join(__dirname, "../", "../index.html"));
        } else {
            // 环境变量VITE_DEV_SERVER_HOST和VITE_DEV_SERVER_PORT在vite-plugin-electron插件中默认定义
            const url = `http://${process.env["VITE_DEV_SERVER_HOST"]}:${process.env["VITE_DEV_SERVER_PORT"]}`;

            win.loadURL(url);
        }
        //注册名称
        win.webContents.on('did-finish-load', () => {
            // 二、注册窗口id
            registerWindowId('Main', win.webContents.id);
        })

        win.webContents.on('destroyed', () => {
            // 三、销毁窗口 id
            removeWindowId('Main');
        })
        //全局播放
        globalShortcut.register('Ctrl+Alt+Left',()=>{
            win.webContents.send('main-prev')
        })
        globalShortcut.register('Ctrl+Alt+P',()=>{
            win.webContents.send('main-play')
        })
        globalShortcut.register('Ctrl+Alt+Right',()=>{
            win.webContents.send('main-next')
        })
        //歌词请求出现详情页面
        ipcMain.on('lrc-open-playDetail',()=>{
            win.show()
        })
        //召唤拖拽窗口
        return win
    })
};

export const childWindw = (): any => {
    const child = new BrowserWindow({
        frame: false, //隐藏默认控件
        transparent: true,
        backgroundColor: '#00000000',
        hasShadow:false,
        minWidth:616,
        minHeight:123,
        width:616,
        height:123,
        maxHeight:291,
        show: false,
        skipTaskbar: true,
        // titleBarStyle:'hidden'
        webPreferences: {
            nodeIntegration: true,
            // contextIsolation: false,
            preload: path.join(__dirname, "../preload/index.js"),
        },
    })
    child.webContents.toggleDevTools()
    //注册名称
    child.webContents.on('did-finish-load', () => {
        // 二、注册窗口id
        registerWindowId('Ci', child.webContents.id);
    })
    
    child.webContents.on('destroyed', () => {
        // 三、销毁窗口 id
        removeWindowId('Ci');
    })
    child.loadURL(`http://${process.env["VITE_DEV_SERVER_HOST"]}:${process.env["VITE_DEV_SERVER_PORT"]}/#/lyric`)

    function SendXY(){
        child.webContents.send('lyric-x-y',{x:child.getSize()[0],y:child.getSize()[1]})
    }

    child.on('will-resize',SendXY)
    //得到宽高
    ipcMain.on('get-child-x-y',(event)=>{
        event.returnValue = {x:child.getSize()[0],y:child.getSize()[1]}
    })

    //移动
    let X,Y;
    let screenMoveChil:any;
    ipcMain.on('move-child',(e,obj)=>{
        let {mouseX,mouseY,width,height} = obj;
        let { x, y } = child.getBounds();  //左上点坐标
        if(!screenMoveChil){
            screenMoveChil = setInterval(() => {
                X = screen.getCursorScreenPoint().x
                Y = screen.getCursorScreenPoint().y
                child.setBounds({width:width,height:height,x:x + (X - (mouseX + x)),y:y + (Y - (mouseY + y))})
            }, 10)
        }
    })
    ipcMain.on('destory-move-child',()=>{
        clearInterval(screenMoveChil)
        screenMoveChil = null;
    })

    //打开歌词子窗口
    ipcMain.on('open-lyric', (e, flag) => {
        child.setAlwaysOnTop(true, 'pop-up-menu')
        if (flag == true) {
            child.show()
        } else {
            child.hide();
        }
    })

    //锁定与不锁定
    ipcMain.on('no-resizable',()=>{
        child.setResizable(false)
    })
    ipcMain.on('can-resizable',()=>{
        child.setResizable(true)
    })

    ipcMain.on('mouse-can',()=>{
        child.setIgnoreMouseEvents(false)
    })
    ipcMain.on('mouse-no',()=>{
        child.setIgnoreMouseEvents(true,{forward:true})
    })


    return child
}

export const dragWindw = ():BrowserWindow=>{
    const win = new BrowserWindow({
        width:100,
        height:23,
        minHeight:0,
        frame: false,
        // show:false,
        transparent: true,
        backgroundColor: '#00000000',
        // useContentSize:true,
        skipTaskbar: true,
        alwaysOnTop:true,
        // titleBarStyle:'hidden'
        webPreferences: {
            nodeIntegration: true,
            // contextIsolation: false,
            preload: path.join(__dirname, "../preload/index.js"),
        },
    })
    win.setPosition(9999,9999)
    win.webContents.on('did-finish-load', () => {
        // 二、注册窗口id
        registerWindowId('drageMessage', win.webContents.id);
    })
    win.webContents.on('destroyed', () => {
        // 三、销毁窗口 id
        removeWindowId('drageMessage');
    })
    Menu.setApplicationMenu(null);
    win.setContentSize(100, 25)
    win.setSize(100, 25)
    win.setIgnoreMouseEvents(true)
    // win.webContents.toggleDevTools()
    win.loadURL(`http://${process.env["VITE_DEV_SERVER_HOST"]}:${process.env["VITE_DEV_SERVER_PORT"]}/#/dragMessage`)

    let ifChanged = false
    let hM = 25
    let wM = 25
    ipcMain.on('change-drag-width',(e,message)=>{
        if(message.width + 5 < 25){
            wM = 25
            hM = 25
        }else{
            wM = message.width + 5
            hM = 25
        }
        ifChanged = true
    })
    let mouseListener:any
    ipcMain.on('begin-drag',(e)=>{
        // let {message,backGroundColor} = messageObj
        let X = screen.getCursorScreenPoint().x
        let Y = screen.getCursorScreenPoint().y
        win.setPosition(X+30,Y)
        if(!mouseListener){
            mouseListener = setInterval(()=>{
                if(ifChanged){
                    X = screen.getCursorScreenPoint().x
                    Y = screen.getCursorScreenPoint().y
                    win.setContentBounds({width:wM,height:hM,x:X+30,y:Y})
                }
            },10)
        }
        win.showInactive()
    })
    ipcMain.on('end-drag',(e)=>{
        clearInterval(mouseListener)
        mouseListener = null
        ifChanged = false
        win.hide()
    })
    return win
}